// HDB3解码器


module HDB3_decoder (
    clk,rst_n,in,out
);

input  wire clk,rst_n;
input  wire [1:0] in;
output reg out;

parameter one_pos = 2'b01,zero_out = 2'b00,one_neg = 2'b10;
parameter zero = 2'b00,one = 2'b01,B = 2'b10,V = 2'b11;

reg [1:0] last_in;
reg [1:0] temp1;// 记录第一次转换的结果，找出V，其他的非零替换成1
reg [1:0] temp2;
reg [1:0] buffer1,buffer2,buffer3;

// assign out = temp1;

// 确定V和B的位置
// 确定V的位置，若一个非零的值和上一个非零的值相等，则这个非零的值为V
always @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
        temp1 <= 0;
    end
    else begin
        if (in == zero_out) begin
            temp1 <= zero;
        end
        else begin
            last_in <= in;// 记录上一个非零的值
            if (in == last_in) begin
                temp1 <= V;
            end
            else begin
                temp1 <= one;
            end
        end
    end
end

// 找出B，并将其置零
always @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
        out <= 0;
    end
    else begin
        if (temp1 == V) begin
            temp2 <= zero;
        end
        else temp2 <= buffer3;
        case (temp2)
            zero:out <= 0;
            one:out <= 1;
            V:out <= 0;
            default:out <= 0;
        endcase
    end
end

// buffer，延时三个时钟周期
always @(posedge clk) begin
    buffer1 <= temp1;
    buffer2 <= buffer1;
    buffer3 <= buffer2;
end

endmodule //HDB3_decoder